package com.niknik.woody.core.room;

import com.google.inject.Inject;
import com.google.inject.name.Named;
import com.niknik.woody.rest.schema.ResLogMsg;
import com.niknik.woody.utils.Check;
import com.niknik.woody.utils.WSchema;

import java.util.Date;

public class Room {

  public static final String MAX_ROOM_IDLE_MILLIS = WSchema.NIKNIK_NAMESPACE + ".woody.core.room.max_idle_millis";

  @Inject Game game;
  @Inject RoomRegistry roomRegistry;
  @Inject @Named(Room.MAX_ROOM_IDLE_MILLIS) private long maxRoomIdleMillis;

  private String id;
  private long lastMoveMillis;

  public String getDescription() {
    return game.getDescription();
  }

  public void move(String playerId, String data)
      throws GameEx {
    Check.state(isActive(), ResLogMsg.ROOM_IS_INACTIVE, id.toString());
    this.game.move(playerId, data);
    lastMoveMillis = new Date().getTime();
  }

  public String getId() {
    return id;
  }

  public void close() {
    game = null;
    roomRegistry.delete(id);
  }

  public Boolean isActive() {
    return new Date().getTime() - lastMoveMillis < maxRoomIdleMillis;
  }

  void init(String id) {
    this.id = id;
    lastMoveMillis = new Date().getTime();
    game.setRoom(this);
  }
}

